<template>
  <div class="app-container" v-loading="loading" element-loading-text="拼命加载中">
    <div class="gndy">
      <div class="sx_top">
        <!-- <span class="top_span2" style="margin-right: 14px">登录地址</span>
        <el-input size="mini" style="margin-right: 14px; width: 240px; margin-top: 27px" placeholder="请输入"
          v-model="loginAdress" clearable /> -->
        <!-- <span class="top_span2" style="margin-right: 14px">用户名称</span>
        <el-input
          size="mini"
          style="margin-right: 14px; width: 240px; margin-top: 27px"
          placeholder="请输入"
          v-model="info.userName"
        /> -->
        <span class="top_span2" style="margin-right: 14px">状态</span>
        <el-select v-model="loginStatus" size="mini" placeholder="请选择" style="width: 240px; margin-top: 27px" clearable>
          <el-option label="成功" :value="true" />
          <el-option label="失败" :value="false" />
        </el-select>
        <span class="top_span2" style="margin-right: 14px; margin-left: 14px">登录时间：</span>
        <el-date-picker clearable v-model="logonDate" size="mini" :picker-options="options" format="yyyy-MM-dd HH:mm"
          type="datetime" placeholder="请选择" style="width: 240px;" />
        <div style="margin-top: 14px">
          <el-button size="mini" style="margin-right: 10px" type="primary" @click="handleSearchClick">查 询</el-button>
          <el-button size="mini" @click="handleReset">重 置</el-button>
        </div>
      </div>
      <div class="juads_div">
        <div style="margin-bottom: 12px">
          <el-button type="primary" style="margin-right: 10px;" @click="getLoginCopy" icon="el-icon-download"
            size="mini">登录日志拷贝</el-button>
        </div>
        <div class="table_div">
          <el-table height="calc(100vh - 410px)" :data="newListData"
            @selection-change="handleSelectionChange" style="width: 100%" :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{
							background: 'rgba(250, 250, 250, 1)',
							textAlign: 'center',
            }">
            <!-- <el-table-column type="selection" width="55" /> -->
            <el-table-column prop="username" label="用户名称" />
            <el-table-column label="登录地址">
              <template slot-scope="scope">
                本机
              </template>
            </el-table-column>
            <el-table-column prop="browser" label="浏览器" />
            <el-table-column prop="os" label="操作系统">Win10</el-table-column>
            <el-table-column label="登录状态" align="center" prop="status">
              <template slot-scope="scope">
                <dict-tag :value="scope.row.status" />
                <el-tag size="medium"
                  :type="scope.row.status?'success':'danger'">{{scope.row.status?'成功':'失败'}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="message" label="操作信息" />
            <el-table-column label="登录时间" :formatter="handleFormatter" />
          </el-table>
          <div class="fenye_div">
            <el-pagination background :current-page="pageNo" :page-sizes="[100, 200, 300, 400]" :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="count"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import * as XLSX from "xlsx";
  import { getUserLoginLog, getLoginCopy } from "@/api/user";

  export default {
    name: "loginLog",
    data() {
      return {
        loading: false,
        count: 0,
        options: {
          // 时间不能大于当前时间
          disabledDate: time => {
            return (time.getTime() - 8.64e7) > (Date.now() - 24 * 60 * 60 * 1000);
          },
          // selectableRange: "00:00:00 - 23:59:59"
        },
        ip: "",
        dicts: ['sys_common_status'],
        loginAdress: "",
        userName: "",
        loginStatus: null,
        logonDate: null,
        pageNo: 1,
        pageSize: 100,
        list: [],
        newListData: [],
        multiSelectedGroups: []
      };
    },
    created() {
      console.log("process", process.env);
      this.getUserIP((ip) => {
        //注意：有的浏览器获取到的是IPv4地址，有的是IPv6地址 
        this.ip = ip;
        this.getUserLoginLog();
        console.log("ip地址", ip);
        localStorage.setItem("IP", ip);
      });
    },
    methods: {
      async getLoginCopy() {
        try {
          this.loading = true;
          const info = {
            // ip: this.loginAdress ? this.loginAdress : this.ip,
            status: this.loginStatus,
            loginTimeInSecond: this.logonDate ? Math.floor(this.logonDate / 1000) : 0,
            pageNo: this.pageNo,
            pageSize: this.pageSize
          };
          const { code, result } = await getLoginCopy(info);
          if (code == 0) {
            this.loading = false;
            const src = `${process.env.VUE_APP_BASE_API}${result}`;
            window.open(src, "_self");
          }
        } catch (error) {
          this.loading = false;
          console.log(error);
        }
      },
      handleSearchClick() {
        this.getUserLoginLog();
      },
      handleFormatter(row) {
        return `${new Date(row.loginTime).getFullYear()}-${new Date(row.loginTime).getMonth() + 1}-${new Date(row.loginTime).getDate()} ${new Date(row.loginTime).getHours()}:${new Date(row.loginTime).getMinutes() < 10 ? "0" + new Date(row.loginTime).getMinutes() : new Date(row.loginTime).getMinutes()}`;
      },
      formatterFun(time) {
        return `${new Date(time).getFullYear()}-${new Date(time).getMonth() + 1}-${new Date(time).getDate()}`;
      },
      async getUserLoginLog() {
        try {
          this.loading = true;
          const info = {
            // ip: this.loginAdress ? this.loginAdress : this.ip,
            status: this.loginStatus,
            loginTimeInSecond: this.logonDate ? Math.floor(this.logonDate / 1000) : 0,
            pageNo: this.pageNo,
            pageSize: this.pageSize
          };
          const { code, result: { data, totalCount } } = await getUserLoginLog(info);
          if (code == 0) {
            this.loading = false;
            console.log("list", data);
            this.count = totalCount;
            this.list = data;
            this.newListData = JSON.parse(JSON.stringify(this.list));
          }
        } catch (error) {
          this.loading = false;
          console.log(error);
        }
      },
      getUserIP(onNewIP) {
        let MyPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
        let pc = new MyPeerConnection({
          iceServers: []
        });
        let noop = () => {
        };
        let localIPs = {};
        let ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
        let iterateIP = (ip) => {
          if (!localIPs[ip]) onNewIP(ip);
          localIPs[ip] = true;
        };
        pc.createDataChannel('');
        pc.createOffer().then((sdp) => {
          sdp.sdp.split('\n').forEach(function (line) {
            if (line.indexOf('candidate') < 0) return;
            line.match(ipRegex).forEach(iterateIP);
          });
          pc.setLocalDescription(sdp, noop, noop);
        }).catch((reason) => {
        });
        pc.onicecandidate = (ice) => {
          if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
          ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
        };
      },
      handleSelectionChange(list) {
        this.multiSelectedGroups = [...list];
      },
      // 导出excel
      exportExcel() {
        if (!this.multiSelectedGroups.length) {
          this.$message("请选择要拷贝的日志");
        }
        // this.sheets = this.sheetData(this.filterTableData);
        this.sheets = this.sheetData(this.multiSelectedGroups);

        const wb = XLSX.utils.book_new(); // 创建一个新的workbook

        // 循环添加每个sheet
        this.sheets.forEach(sheet => {
          const ws = XLSX.utils.aoa_to_sheet(sheet.data); // 将json转换为sheet
          XLSX.utils.book_append_sheet(wb, ws, sheet.name); // 向workbook中添加sheet
        });

        // 导出excel
        const wopts = { bookType: "xlsx", bookSST: false, type: "array" };
        const wbout = XLSX.write(wb, wopts);
        const blob = new Blob([wbout], { type: "application/octet-stream" });
        const href = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = href;
        link.download = "登录日志总集.xlsx";
        link.click();
        setTimeout(function () {
          URL.revokeObjectURL(href);
        }, 100);
      },
      sheetData(data) {
        const classifiedData = data.reduce((acc, obj) => {
          const name = obj.name;
          const existingItem = acc.find(item => item.name === name);

          if (existingItem) {
            existingItem.data.push([
              obj.userName,
              obj.loginAdress,
              obj.loginLocation,
              obj.browser,
              obj.operatingSystem,
              obj.loginStatus,
              obj.operationalInformation,
              obj.logonDate
            ]);
          } else {
            acc.push({
              name,
              data: [
                [
                  "用户名称",
                  "登录地址",
                  "登录地点",
                  "浏览器",
                  "操作系统",
                  "登录状态",
                  "操作信息",
                  "登录日期"
                ],
                [
                  obj.userName,
                  obj.loginAdress,
                  obj.loginLocation,
                  obj.browser,
                  obj.operatingSystem,
                  obj.loginStatus == 1 ? "成功" : "失败",
                  obj.operationalInformation,
                  obj.logonDate
                ]
              ]
            });
          }

          return acc;
        }, []);
        return classifiedData;
      },
      handleReset() {
        this.loginAdress = "";
        this.loginStatus = null;
        this.logonDate = "";
        this.getUserLoginLog();
      },
      handleSizeChange(pageSize) {
        this.pageSize = pageSize;
        this.getUserLoginLog();
      },
      handleCurrentChange(pageNo) {
        this.pageNo = pageNo;
        this.getUserLoginLog();
      }
    }
  };
</script>

<style lang="scss">
  .gndy {
    height: 100%;
    padding-bottom: 20px;
    box-sizing: border-box;

    .juads_div {
      height: calc(100vh - 229px);
      margin-top: 20px;
      background-color: #fff;
      box-sizing: border-box;
      padding: 20px;
    }

    .table_div {
      height: calc(100vh - 250px);
    }

    .fenye_div {
      margin-top: 30px;
      text-align: right;
    }

    .top_span2 {
      /** 文本1 */
      font-size: 14px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
    }

    .sx_top {
      height: 120px;
      background-color: #fff;
      box-sizing: border-box;
      padding-left: 36px;
    }
  }
</style>